#! /bin/gawk -f
#
# Script to extract records from an Aqua "dbas"-formatted file.
# Parameters to pass:
#   list (0/1): if (list) exit after printing record list
#   nohdr (0/1): if (nohdr) don't print header lines, i.e. lines starting with $
#   ofil (string): output file name
#

function printit( string ) {
    if ( ofil == "-" )
	print string
    else
	print string > ofil
}

BEGIN {
    if ( ARGC <= 1 ) {
       print "usage: qext [-v list=1] [-v nohdr=1] [-v ofil=outputfile] file"
       exit( 1 )
    }
    print "The DATA records are:"
    nrec = 0
    while ( "grep '$ DATA' " FILENAME | getline ) {
	sub( /\$ DATA */, "" )
	rec[++nrec] = $0
	print nrec ": " $0
    }
    close ( "grep '$ DATA' " FILENAME )
    if ( list )
	exit( 0 )

    printf "Enter your choice (0 to end): "
    getline < "-"
    nsel = $1
    if ( nsel == 0 )
	exit( 0 )
    if ( nsel < 0 || nsel > nrec ) {
	print "Illegal value - no data extracted"
	exit( 1 )
    }
    sel = "\\$ DATA *" rec[nsel]

    if ( ofil == "" ) {
	printf "Enter output file name (- for stdout): "
	getline ofil < "-"
    }

#    if ( ofil != "-" ) {
#	printf "Ignore header? (y/n): "
#	getline < "-"
#	nohdr = ( $0 == "y" || $0 == "Y" )
#    }
}

/END/ {
    doext = 0
    next
}

$0 ~ sel {
    doext = 1
}

doext == 1 {
    if ( $1 == "$" ) {
	if ( !nohdr ) printit( $0 )
	if ( $2 == "TABLE" ) {
	    getline
	    if ( !nohdr ) printit( $0 )
	}
    }
    else
	printit( $0 )
    next
}
